package com.emm.yixun.marketing.service.impl;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.SalesGroupService;
import com.emm.yixun.basic.service.SalesGroupUserService;
import com.emm.yixun.basic.service.SalesTargetPmoService;
import com.emm.yixun.basic.service.SalesTargetService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.SalesGroup;
import com.emm.yixun.common.model.SalesGroupUser;
import com.emm.yixun.common.model.SalesTarget;
import com.emm.yixun.common.model.SalesTargetPmo;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.dto.SalesCalculation;
import com.emm.yixun.common.model.dto.SalesGroupDto;
import com.emm.yixun.common.model.dto.SalesGroupUserDto;
import com.emm.yixun.common.model.dto.SalesTargetDto;
import com.emm.yixun.common.model.dto.SalesTargetPmoDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.SalesTargerEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.marketing.service.SalesTargetServiceFacade;

@Service("salesTargetServiceFacade")
@WebService(name="com.emm.yixun.marketing.service.SalesTargetServiceFacade")
public class SalesTargetServiceFacadeImpl implements SalesTargetServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private SalesTargetService service;
	
	@Autowired
	private SalesGroupService salesGroupService;

	@Autowired
	private SalesGroupUserService salesGroupUserService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private ProjectService projectService;
	@Autowired
	private DataPermissionService dataPermissionService;
	
	@Autowired
	private SalesTargetPmoService salesTargetPmoService;
	
	@Override
	public Response<SalesTargetDto> save(SalesTargetDto dto,List<SalesTargetDto> list ,User user) {
		Response<SalesTargetDto> response=new Response<SalesTargetDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			SalesTargetPmoDto pmo = new SalesTargetPmoDto();
			pmo.setProjectId(dto.getProjectId());
			pmo.setQuotaType(dto.getQuotaType());
			pmo.setSalesYear(dto.getSalesYear());
			//先删除
			salesTargetPmoService.destroy(pmo);
			//P3需求   累计数据新增到PMO表(lsh)
			if(!StringUtils.isEmpty(dto.getPmoJson())){
				SalesTargetPmoDto pmoEntity = JSONObject.parseObject(dto.getPmoJson(),SalesTargetPmoDto.class);
				pmoEntity.setProjectId(dto.getProjectId());
				pmoEntity.setQuotaType(dto.getQuotaType());
				pmoEntity.setSalesYear(dto.getSalesYear());
				pmoEntity.setCreateTime(new Date());
				pmoEntity.setDelFlag(DelFlagEnum.UNDEL.getNo());
				salesTargetPmoService.create(pmoEntity);
			}
			
			//验证
			 Validator validator = new Validator(); 
			 List<ConstraintViolation> ret = validator.validate(dto);
			 if(ret!=null&&ret.size()>0){
				 response.setSuccess(false);
				 response.setResultMessage(ret.get(0).getMessage());
				 return response; 
			 }else{
				//先删除在新增,保存/编辑通用
					SalesTargetDto deleteDto = new SalesTargetDto();
					deleteDto.setProjectId(dto.getProjectId());
					deleteDto.setQuotaType(dto.getQuotaType());
					deleteDto.setSalesYear(dto.getSalesYear());
					service.destroy(deleteDto);
					SalesTargetDto mDto= new SalesTargetDto();
					Project project=projectService.selectById(dto.getProjectId());
					for (SalesTargetDto obj:list) {
						obj.setProjectCode(project.getProjectCode());
						obj.setProjectId(project.getId());
						obj.setSalesYear(dto.getSalesYear());
						obj.setQuotaType(dto.getQuotaType());
						obj.setMerchantId(user.getMerchantId());
						obj.setAccessCode(project.getAccessCode());
						obj.setUserCode(user.getUserCode());
						obj.setCreateUserId(user.getId());
						obj.setCreateTime(new Date());
						obj.setUpdateTime(new Date());
						obj.setDelFlag("0");
						mDto=service.create(obj);
					}
					if(null==mDto){
						response.fail("80000", "保存数据错误");
						return response;
					}
					response.success(mDto);
			 }
			
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(SalesTargetDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto || null==dto.getId()){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=service.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			SalesTargetDto mDto=new SalesTargetDto();
			mDto.setId(id);
			int count=service.destroy(mDto);
			if(count>0){
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<SalesTarget> findById(Long id) {
		Response<SalesTarget> response=new Response<SalesTarget>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			SalesTarget entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<SalesTarget> findByDto(SalesTargetDto dto) {
		ResponseList<SalesTarget> response=new ResponseList<SalesTarget>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<SalesTarget> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<SalesTargetDto> findPageByDto(SalesTargetDto dto, Integer begin,Integer row) {
		Page<SalesTargetDto> response=new Page<SalesTargetDto>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<SalesTargetDto> page = service.getModelPage(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}else{
				for (int i=0;i<page.getRows().size();i++) {
					SalesTargetDto entity = page.getRows().get(i);
					if(StringUtils.isEmpty(entity.getQuotaType())){
						if(i%2==0){
							entity.setQuotaType("0");
						}else{
							entity.setQuotaType("1");
						}
					}
				}
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}

	@Override
	public List<SalesTargetDto> findAddList(Long projectId, Long type,String salesYear) {
		List<SalesTargetDto> salesTargetList = new ArrayList<SalesTargetDto>();
		try {
			SalesGroupDto salesDto = new SalesGroupDto();
			salesDto.setDelFlag("0");
			salesDto.setProjectId(projectId);
			salesDto.setStatus("0");
			List<SalesGroup> salesGroupList = salesGroupService.selectListByDto(salesDto);
			for (SalesGroup objGroup:salesGroupList) {
				SalesGroupUserDto querydto = new SalesGroupUserDto();
				querydto.setSalesGroupId(objGroup.getId());
				querydto.setDelFlag("0");
				querydto.setStatus("0");
				List<SalesGroupUser> groupUserList = salesGroupUserService.selectListByDto(querydto);
				for (SalesGroupUser userObj:groupUserList) {
					SalesTargetDto targerBean = new SalesTargetDto();
					SalesTargetDto targetDto = new SalesTargetDto(); 
					targerBean.setSalesGroupId(userObj.getSalesGroupId());
					targerBean.setSalesGroupUserId(userObj.getUserId());
					targerBean.setQuotaType(type.toString());
					targerBean.setSalesYear(salesYear);
					targerBean.setDelFlag("0");
					SalesTarget tarEntity = 	service.selectByDto(targerBean);
					if(tarEntity!=null){
						targetDto=BeanUtil.convert2T(targetDto,tarEntity);
					}else{
						targetDto.setSalesGroupId(userObj.getSalesGroupId());
						targetDto.setSalesGroupUserId(userObj.getUserId());
					}
					targerBean.setSalesGroupId(userObj.getSalesGroupId());
					targerBean.setSalesGroupUserId(userObj.getUserId());
					targetDto.setSalesGroupName(objGroup.getName());
					User user=userService.selectById(userObj.getUserId());
					targetDto.setUserName(user.getUserName());
					salesTargetList.add(targetDto);
				}
			}
			return salesTargetList;
		} catch (Exception e) {
			logger.error("findAddList error: ", e);
		}
		return null;
	}

	@Override
	public List<SalesTargetDto> findSumList(SalesTargetDto dto) {
		List<SalesTargetDto> array = new ArrayList<SalesTargetDto>();
		try {
			Long projectId = dto.getProjectId();
			String salesYear = dto.getSalesYear();
			ProjectDto entity = new ProjectDto();
			entity.setDelFlag("0");
			entity.setId(projectId);
			entity.setResourcesCode("menu_0003_0001");
			entity.setMerchantId(dto.getMerchantId());
			//数据权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(), dto.getResourcesCode(), entity.getPrefix(), entity.getColumnName());
				String [] dataPermissionArr = dataPermission.split(":");
				if("00".equals(dataPermissionArr[0])){
					return array;
				}
				entity.setDataPermission(dataPermissionArr[1]);
			}
			
			List<Project> projectList =	projectService.selectListByDto(entity);
			for (Project proObj:projectList) {
				SalesTargetDto targetdto = new SalesTargetDto();
				targetdto.setProjectId(proObj.getId());
				targetdto.setDelFlag("0");
				targetdto.setSalesYear(salesYear);
				List<SalesTargetDto> arrayList = addList(targetdto, proObj);
				
				array.addAll(arrayList);
				
			}
		/*	for (int i = 0; i < array.size(); i++) {
				System.out.println(array.get(i).getProjectName()+","
						+array.get(i).getQuotaType()+","+array.get(i).getProjectId());
			}*/
			return array;
		} catch (Exception e) {
			logger.error("findSumList error: ", e);
		}
		return null;
	}

	public List<SalesTargetDto> addList(SalesTargetDto targetdto,Project proObj){
		List<SalesTargetDto> array = new ArrayList<SalesTargetDto>();
		//累计对象
		Map<String, SalesTargetDto> map = new HashMap<String, SalesTargetDto>();
		for (SalesTargerEnum sales:SalesTargerEnum.values()) {
			targetdto.setQuotaType(sales.getNo().toString());
		
			if(sales.isIs_sum()){
				//累加需要累计对象的数据值
				SalesTargetDto mapValue = map.get(proObj.getId()+"-"+sales.getSalesNumber());
				
				SalesTarget result = BeanUtil.convert2T(new SalesTarget(), mapValue);
				SalesTargetDto value =convestResult(result);
				value.setProjectName(proObj.getProjectName());
				value.setQuotaType(sales.getNo().toString());
				array.add(value);
			}else{
//				SalesTargetDto targetObj = service.sumByProjectId(targetdto);
//				if(targetObj!=null&&targetObj.getId()!=null){
//					convert(targetdto);
//					targetObj.setProjectId(proObj.getId());
//					targetObj.setProjectName(proObj.getProjectName());
//					targetObj.setQuotaType(targetdto.getQuotaType());
//					array.add(targetObj);
//					map.put(proObj.getId()+"-"+targetdto.getQuotaType(), targetObj);
//				}else{
//						SalesTargetDto target = new SalesTargetDto();
//						target.setProjectId(proObj.getId());
//						target.setProjectName(proObj.getProjectName());
//						target.setQuotaType(targetdto.getQuotaType());
//						array.add(target);
//						map.put(proObj.getId()+"-"+targetdto.getQuotaType(), target);
//				}
				//修改为获取指标类型值
				SalesTargetDto targetObj = new SalesTargetDto();
				SalesTargetPmoDto entity = new SalesTargetPmoDto();
				entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
				entity.setProjectId(targetdto.getProjectId());
				entity.setQuotaType(targetdto.getQuotaType());
				entity.setSalesYear(targetdto.getSalesYear());
				SalesTargetPmo pmo = salesTargetPmoService.sumByProjectId(entity);
				if(pmo != null){
					BeanUtils.copyProperties(pmo, targetObj);
					targetObj.setProjectId(proObj.getId());
					targetObj.setProjectName(proObj.getProjectName());
					targetObj.setQuotaType(targetdto.getQuotaType());
					array.add(targetObj);
					map.put(proObj.getId()+"-"+targetdto.getQuotaType(), targetObj);
				}else{
					targetObj.setProjectId(proObj.getId());
					targetObj.setProjectName(proObj.getProjectName());
					targetObj.setQuotaType(targetdto.getQuotaType());
					array.add(targetObj);
					map.put(proObj.getId()+"-"+targetdto.getQuotaType(), targetObj);
				}
			}
		}
		return array;
	}
	
	/**
	* 方法描述 : 需要累加的对象
	* 创建者：ThinkPad 
	* 项目名称： emm-marketing
	* 类名： SalesTargetServiceFacadeImpl.java
	* 版本： v1.0
	* 创建时间： 2017年3月21日 下午2:20:56
	* @param obj
	* @return SalesTargetDto
	 */
	public SalesTargetDto convestResult(SalesTarget obj){
		SalesTargetDto sumbit = new SalesTargetDto();
		/*BeanUtil.convert2T(sumbit, obj);*/
		try {
			ArrayList<BigDecimal> array = new ArrayList<BigDecimal>();
			Class<?> tClass = obj.getClass();
			Field[] fields = tClass.getDeclaredFields();
			for (int j = 0; j < fields.length; j++) {
				String type = fields[j].getGenericType().toString();
				if(type.equals("class java.math.BigDecimal")){
					String name = fields[j].getName(); 
					name = name.substring(0, 1).toUpperCase() + name.substring(1);
					Method m = obj.getClass().getMethod("get" + name);
					Object val = m.invoke(obj);
					if(val!=null){
						BigDecimal value = (BigDecimal)val;
						array.add(value);
					}
				}
			}
			SalesCalculation calculation = new SalesCalculation();
			Field[] calcuationFidlds = calculation.getClass().getDeclaredFields();
			for (int i = 0; i < calcuationFidlds.length; i++) {
				calcuationFidlds[i].setAccessible(true);
				calcuationFidlds[i].set(calculation, calculation(array, i));
			}
			BeanUtil.convert2T(sumbit, calculation);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sumbit;
	}
	
	public BigDecimal calculation(ArrayList<BigDecimal> array,Integer end){
		BigDecimal value = new BigDecimal(0);
		for (int i = 0; i <= end; i++) {
			value=value.add(array.get(i));
		}
		return value;
	}

	@Override
	public Response<Boolean> clearSalesTarget(SalesTargetDto dto) {
		Response<Boolean> response = new Response<Boolean>();
		try {
			service.destroy(dto);
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			e.printStackTrace();
		}
		return response;
	}

	@Override
	public ResponseList<SalesTargetPmo> findCumulativeGrid(SalesTargetPmoDto dto) {
		ResponseList<SalesTargetPmo> responseList = new ResponseList<SalesTargetPmo>();
		try {
			List<SalesTargetPmo> array = new ArrayList<SalesTargetPmo>();
			
			dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			SalesTargetPmo pmo = salesTargetPmoService.selectByDto(dto);
			if(pmo!=null){
				array.add(pmo);
			}else{
				array.add(dto);
			}
			responseList.setSuccess(true);
			responseList.setEntity(array);
		} catch (Exception e) {
			responseList.setSuccess(false);
			logger.error("findCumulativeGrid error: ", e);
		}
		return responseList;
	}
}
